import React, { Component } from "react";
import { message, Modal,Checkbox } from "antd";
import FromCom from "components/form";
import { validateEmail, validatePhone } from "utils/validate.js";
import { custom } from "api/common";
import CryptoJs from "crypto-js";
import {GetRole} from 'api/permission'
import CheckBoxAll from 'components/checkboxAll/Index.js'
import store from 'store/index'
import *as TYPES from 'store/action-types'

 class ModalCom extends Component {
  constructor() {
    super();
    // ref
    this.fromCom = React.createRef();
    // 数据
    this.state = {
      isModalVisible: false,
      // 表单
      formLayout: {
        labelCol: { span: 7 },
        wrapperCol: { span: 17 },
      },
      formItem: [
        {
          type: "Input",
          label: "邮箱",
          name: "username",
          required: true,
          style: { width: "250px" },
          placeholder: "请输入邮箱",
          rules: [
            ({ getFieldValue }) => ({
              validator(rule, value) {
                if (value && validateEmail(value)) {
                  return Promise.reject("请输入正确邮箱！");
                }
                return Promise.resolve();
              },
            }),
          ],
        },
        {
          type: "Input",
          label: "真实名称",
          name: "truename",
          required: true,
          style: { width: "250px" },
          placeholder: "请输入姓名",
        },
        {
          type: "Input",
          label: "密码",
          name: "password",
          required: true,
          style: { width: "250px" },
          placeholder: "请输入密码",
        },
        {
          type: "Input",
          label: "手机号",
          name: "phone",
          required: true,
          style: { width: "250px" },
          placeholder: "请填写手机号",
          rules: [
            ({ getFieldValue }) => ({
              validator(rule, value) {
                if (value && validatePhone(value)) {
                  return Promise.reject("请输入正确手机号码！");
                }
                return Promise.resolve();
              },
            }),
          ],
        },
        {
          type: "Select",
          label: "禁启用",
          options: "status",
          style: { width: "250px" },
          name: "status",
          required: true,
        },
        {
          type:"Slot",
          label:'权限',
          name: "role",
          slotName:'role',
          style: { width: "250px" },
        },
        {
          type:"Slot",
          label:'菜单权限',
          name: "role_menu",
          slotName:'role_menu',
          style: { width: "250px" },
        }
      ],
      editData: {},
      initialValues: {},
      id: null,
      options:[],
      getPermVal:[],
      // 菜单权限 
      role_menu:[
        {
          // 一级 
          label:'用户管理',
          value:'/user',
          // 子级
          child_item:[
            {label:'用户列表',value:'/user/list'},
            {label:'用户添加',value:'/user/add'}
          ]
        },
        {
          // 一级 
          label:'部门管理',
          value:'/department',
          // 子级
          child_item:[
            {label:'部门列表',value:'/department/list'},
            {label:'添加部门',value:'/department/add'}
          ]
        }
      ]
    };
  }
  componentDidMount(){
    this.GetRole()
  }
  
  GetRole =async ()=>{
    //从服务器获得的角色分配权限 
    const res = await GetRole()
    this.setState({
      options:res.data ? res.data : []
    })
  }
  isEdit = (params) => {
    const getPermVal = params.role ? params.role.split(',') : []
    this.setState({  id: params.id, getPermVal:[...getPermVal]}, () => {
        this.isShowModal();
        // 有个bug第一次的时候-渲染不了 可能是因为里面实例还没生成
        this.fromCom.current&&this.fromCom.current.form.current.setFieldsValue(params)
      });
  };
  isShowModal = (isFlag = true) => {
    this.setState({ isModalVisible: isFlag });
  };
  handleCancel = () => {
    this.setState({ editData: {}, id: null,getPermVal:[] }, () => {
        this.fromCom.current&&this.fromCom.current.form.current.resetFields()
        // 关闭蒙层 --将redux里面的数据置空 
      store.dispatch({type:TYPES.menuRole, payload:{}})//也可以调用actions里面的那个方法

      this.isShowModal(false);
    });
  };
  // 点击确定按钮
  handleOk = () => {
    this.fromCom.current.onFinish();
  };
  onFinish = async (val, $form) => {
    const { id ,getPermVal } = this.state;
    try {
      const requestData = await $form.validateFields();
      if (!requestData) return;
      if (id) {
        requestData["id"] = id;
      }

      // 处理密码--解密
      requestData.password &&
        (requestData.password = CryptoJs.MD5(requestData.password).toString());
        // 添加角色分配 
        const role = getPermVal.length>0 ? getPermVal.join(',') : '';
        requestData['role'] = role ;
        // 添加菜单权限分配 
        const role_menu = store.getState().menu.role_menu
        let roleStr = ''
        for (const key in role_menu) {
          if (Object.hasOwnProperty.call(role_menu, key)) {
            const element = role_menu[key];
             for (const itm in element) {
               if (Object.hasOwnProperty.call(element, itm)) {
                roleStr = roleStr.concat(itm,',')
               }
             }
          }
        }
         roleStr= roleStr.length>0&&roleStr.substring(0,roleStr.length-1)
        requestData['role_menu'] = roleStr

      const res = await custom({
        url: `${!id ? "/user/add/" : "/user/edit/"}`,
        data: requestData,
      });
      message.success(res.message);
      this.handleCancel();
      $form.resetFields();
      //  刷新页面
      this.props.requestData();
    } catch (error) {
      console.log(error);
    }
  };
  getPerm = (value)=>{
     this.setState({
      getPermVal:value
     })
  }

  render(h) {
    const {
      formLayout,
      formItem,
      editData,
      initialValues,
      isModalVisible,
      options,
      getPermVal,
      role_menu
    } = this.state;
    return (
      <Modal
        title="Basic Modal"
        visible={isModalVisible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        // footer={null}
      >
        <FromCom
          formItem={formItem}
          formLayout={formLayout}
          submit={this.onFinish}
          editData={editData}
          initialValues={initialValues}
          isShowBtn={false}
          ref={this.fromCom}
        >
           <Checkbox.Group slot_name='role'  options={options} onChange={this.getPerm} value={getPermVal}/>
           <div slot_name='role_menu'>
              {role_menu.map((item,index)=><CheckBoxAll  roleData={item} key={index}/>)}
           </div>
        </FromCom>
      </Modal>
    );
  }
}
export default ModalCom
